<?php

namespace App\Repositories;

use App\Http\Helper\BeanHelper;
use App\Models\TestingDetail;
use App\Models\TestingItem;
use App\Services\OpensslEncryptHelper;
use Cache;
use TestingDeveloperService;
use App\Services\IdEncryptService;
use TestingConfig;
use UserRecordService;
use ResultTypeService;
use DeveloperLinkService;
use TestingItemService;
use ParamConfig;
class TestingDetailRepository extends Repository
{
    static $tag = 'testing.detail';
    const MULTI_SELECTION_DEFAULT_OPTION_KEY = '以上都不是';

    const CREATE_BY_JZ_CUSTOMER = 'JZ_CUSTOMER';
    const CREATE_BY_SYSTEM = 'SYSTEM';

    public function store($data)
    {
        $this->clearCache(self::$tag);
        $res = TestingDetail::firstOrCreate($data);
        return $res;
    }

    public function getById($id) {
        $cacheKey = getCacheKey('testing.cache_key.testing.info') . $id;

        $cate = $this->remember($cacheKey, function () use ($id) {
            return TestingDetail::where('id', $id)->firstOrFail()->toarray();
        });
        return $cate;
    }

    /**
     * 返回测评列表
     * @param $dev_code 测评所属
     * @return mixed
     */
    public function getList($dev_code)
    {
        $key = getCacheKey('testing.cache_key.testing.list');
        $key = $key . $dev_code;
        $list = $this->remember($key, function () use ($dev_code) {
            return TestingDetail::select('id', 'icon', 'name as title')->where('dev_union_code', $dev_code)->get();
        });
        return $list;
    }

    /**
     * 获取五维测评的列表,使用version字段为2，3为筛选条件，2表示五维测评，3表示五维测评第二版本
     */
    public function getFiveDimesionList()
    {
        $list = TestingDetail::select('id', 'name as title','version')->whereBetween('version',[2,3])->get();
        return BeanHelper::convertStdClsToArr($list);
    }

    /**根据tid获取测试名称
     * @param $tid
     * @return mixed
     */
    public function getNameByTid($tid){
        $cacheKey = getCacheKey('testing.cache_key.testing.name').$tid;
        $data = $this->remember($cacheKey, function () use ($tid) {
            $res = TestingDetail::select('name')->where('id', $tid)->first();
            return $res['name'];
        });
        return $data;
    }

    /**
     * 返回测试题目主题及测试题目列表
     * @param $id
     * @return mixed
     */
    public function getItem($id)
    {
        $key = getCacheKey('testing.cache_key.testing.item');
        $key = $key . $id;
        $iterm = $this->remember($key, function () use ($id) {
            $item = TestingItem::select('index', 'title', 'question_type as questionType', 'options', 'blank_type as blankType')
                ->where('testing_id', $id)
                ->whereIn('question_type', [1, 2, 3, 7, 8])//1单选，2多选，3填空，4关联计算，5自动计算，6动态多选，7单选中自定义输入 8多选中自定义输入
                ->orderBy('index', 'asc')
                ->get();
            foreach ($item as $k => $v) {
                $item[$k]['options'] = json_decode($v['options'], true);
            }
            $data = TestingDetail::where('id', $id)->select('name', 'theme', 'dev_union_code')->first()->toarray();
            switch ($data['theme']) {
                case 2:
                    $data['theme'] = "blue";
                    break;
                case 3:
                    $data['theme'] = "green";
                    break;
                case 4:
                    $data['theme'] = "zhongan";
                    break;
                default:
                    $data['theme'] = "default";
                    break;
            }
            $data['questionList'] = $item;
            $data['route'] = true;

            $developer = TestingDeveloperService::getByUnionCode($data['dev_union_code']);
            //别称
            $data['thirdpartyName'] = $developer['abbreviation'];
            //去掉dev_union_code属性
            unset($data['dev_union_code']);
            return $data;
        });
        return $iterm;
    }

    /**测试提交成功更行测试次数
     * @param $tid
     * @return mixed
     */
    public function updataTestTimes($tid)
    {
        $times = $this->getById($tid);
        return TestingDetail::where('id', $tid)->update(['test_times' => $times['test_times'] + 1]);
    }

    public function getOptions()
    {
        $key = getCacheKey('testing.cache_key.iterm.options');
        $list = $this->remember($key, function () {
            $list = TestingDetail::all();
            $data = [];
            if ($list) {
                $obj = array();
                foreach ($list as $key => $val) {
                    $obj['id'] = $val['id'];
                    $obj['text'] = $val['name'];
                    array_push($data, $obj);
                }
            }
            return $data;
        });
        return $list;
    }

    public function getByUnionCode($union_code)
    {

        $cacheKey = getCacheKey('testing.cache_key.unioncode.info');

        $cacheKey = $cacheKey . $union_code;

        $date = $this->remember($cacheKey, function () use ($union_code) {
            return TestingDetail::where('dev_union_code', $union_code)->get();
        });
        return $date;
    }

    public function handleThirdpartyUid($unionCode,$uid){
        //含有自身uid的接入的第三方测评对应的开发这唯一识别码列表，以逗号分割
        $thirdPartyUnionCodes = TestingConfig::getThirdPartyUnionCodes();
        //如果是通过第三方的用户则直接
        if(!in_array($unionCode,$thirdPartyUnionCodes)){
            //获取uid,解密
            $uid =  IdEncryptService::encryption($uid,'decode');
            $uid = $uid[0];
        }
        return $uid;
    }

    /**
     * 添加用户自定义的问卷
     */
    public function addCustomerQuestionnair($questionnairId){
        $tid = 0;
        //验证重复，如果存在重复的客户问卷编号则直接返回
        if(!$this->getByCustomerQuestionnariId($questionnairId)){
            $jzApiDomain = TestingConfig::getValue('jz.admin.base.url');
            $customerQuestionnairDetailApiPath = TestingConfig::getValue('jz.admin.customer.questionnair.detail.path');
            $requestUrl = $jzApiDomain.$customerQuestionnairDetailApiPath;
            $param = [
                'questionnair_id' => $questionnairId
            ];
            $paramValue = OpensslEncryptHelper::encryptWithOpenssl(json_encode($param));
            $requestUrl.=$paramValue;
            error_log("get customer questionnair detail request url is ==================>".$requestUrl);
            $data = curlRequest($requestUrl);
            error_log("activate  questionnair is==================>".$data);
            $result = json_decode($data,true);
            if($result['errcode'] == 200){
                $devUnionCode = TestingConfig::getValue('testing.display_dev_code');
                $questionnairInfo = $result['data'];
                $items = $questionnairInfo['items'];
                $insertDetailData = [
                    'name' => $questionnairInfo['name'],
                    'cate_id' => $questionnairInfo['cate_id'],
                    'questions_count' => $questionnairInfo['question_count'],
                    'note' => $questionnairInfo['note'],
                    'icon' => 'image/icon3.png',
                    'theme' => 1,
                    'time' => $questionnairInfo['time'],
                    'gist' => $questionnairInfo['gist'],
                    'customer_questionnair_id' => $questionnairInfo['id'],
                    'customer_id' => $questionnairInfo['creator'],
                    'customer_team_id' => $questionnairInfo['team_id'],
                    'create_by' => 'JZ_CUSTOMER',
                    'dev_union_code' => $devUnionCode,
                    'result_type' => 31,
                ];

                //将数据插入到测评库中
                if($saveTestingDetailResult = $this->store($insertDetailData)){
                    $tid = $saveTestingDetailResult['id'];
                    $unsetItemKeys = ['id','questionnair_id','creator','add_time','update_time','modifier'];
                    foreach ($items as &$item){
//                        $item['options'] = json_encode($item['options']);
                        $item = $this->formatAddMultiSelectOption($item);
                        $item['testing_id'] = $tid;
                        $item['customer_item_id'] = $item['id'];
                        $item['options'] = json_encode($item['options']);
                        foreach ($unsetItemKeys as $key){
                            unset($item[$key]);
                        }
                    }
                    //插入题目
                    TestingItemService::batchInsertData($items);
                    //清除列表中的缓存
                    $testingListCacheKey = getCacheKey('testing.cache_key.testing.list');
                    $testingListCacheKey = $testingListCacheKey . $devUnionCode;
                    $this->forget($testingListCacheKey);
                }

            }
        }else{
            //已经存在
            $tid = -1;
        }

        $obj = [
            'tid' => $tid
        ];
        return $obj;
    }

    /**
     * 给多选增加默认选项
     */
    public function formatAddMultiSelectOption($item){
        if($item['question_type'] == 2){
            $multiSelectionDefaultOption = [
                'key' => self::MULTI_SELECTION_DEFAULT_OPTION_KEY,
                'weight' => 0
            ];

            $options = $item['options'];
            $hasDefaultOption = false;
            foreach ($options as $option){
                if($option['key'] == $multiSelectionDefaultOption['key']){
                    $hasDefaultOption = true;
                    break;
                }
            }
            //是否有默认的选项
            if(!$hasDefaultOption){
                array_push($options,$multiSelectionDefaultOption);
            }
            $item['options'] = $options;
        }
        return $item;
    }

    public function getByCustomerQuestionnariId($questionnairId){
        return json_decode(json_encode(TestingDetail::where('customer_questionnair_id', $questionnairId)->first()),true);
    }

    public function selectDevUnionCodeByTid($tid)
    {
        /*  dd($tid);*/
        $cacheKey = getCacheKey('testing.cache_key.testing.detail.info.selectdevunioncodebytid');


        $date = $this->remember($cacheKey, function () use ($tid) {
            return TestingDetail::select('dev_union_code')
                ->where('id', $tid)
                ->firstOrFail()
                ->toarray();
        });
        return $date;
    }

    public function getAll(){
        return TestingDetail::all();
    }

    public function  getTestingResultByUidTid($uid,$tid){

        $data = [];
        $result = UserRecordService::getByUid($uid,$tid);
        if($result){
            $result = ResultTypeService::chooseResult($uid,$tid);
            $data['attrs'] = $result['attrs'];
        }else{
            $data['attrs'] = [];
        }
        return $data;
    }

    public function model()
    {
        return app(TestingDetail::class);
    }

    public function tag()
    {
        return self::$tag;
    }

    /**
     * 根据订单id 和tid获取题目中自动填充的部分
     * @param $tid
     * @param $free_order_id
     * @return array
     */
    public function getItemResult($tid,$free_order_id){
        $item = $this->getItem($tid);
        $data = [];
        if($item){
            $list = $item['questionList'];
            $relation = json_decode(ParamConfig::getValue('JZ.item.order.field.relation.'.$tid),true);
            if($relation){
                $url = TestingConfig::getValue('jz.admin.base.url');
                $path = TestingConfig::getValue('jz.free_order.result.path');
                $url = $url.$path;
                $param = [
                    'id' => $free_order_id,
                ];
                $paramStr = json_encode($param);
                $paramStr = OpensslEncryptHelper::encryptWithOpenssl($paramStr);
                $url = sprintf($url,$paramStr);
                $response  = curlRequest($url);
                $result = json_decode($response,true);
                if($result && $result['errcode'] == 200){
                    $info = $result['data'];
                    foreach($list as $k => $v){
                        if(array_key_exists($v['index'],$relation)){
                            $data[$k] = $info[$relation[$v['index']]];
                        }else{
                            $data[$k] = "";
                        }
                    }
                }
            }
        }
        return $data;
    }
}